use std::sync::Arc;
use crate::entity::ai_user::{Entity as UserMapper, Model as UserModel};

use crate::pojo::{req::UserReq, vo::UserVO};
use common::utils::config_utils::Config;
use common::{
    base::{biz_error::FAIL, dto::SysUser, res::Res},
    enums::cache_key::SYSTEM_USER,
    utils::{
        cache_utils::{CacheType, GlobalCache},
        security_utils,
    },
};
use dyn_fmt::AsStrFormatExt;
use sea_orm::{DatabaseConnection, EntityTrait};
use tracing::info;

pub struct UserService {
    db: Arc<DatabaseConnection>,
    config: Arc<Config>,
}

impl UserService {
    pub fn new(db: Arc<DatabaseConnection>, config: Arc<Config>) -> Self {
        UserService { db, config }
    }

    pub async fn query_by_id(&self, id: i64) -> Res<UserVO> {
        info!("当前查询id:{:?}", id);
        let user = match UserMapper::find_by_id(id).one(&*self.db).await {
            Ok(Some(user)) => user,
            Ok(None) => return Res::build(FAIL),
            Err(_) => return Res::build(FAIL),
        };
        Res::success(user.into())
    }

    pub fn do_err(&self) -> Res<String> {
        panic!("测试异常");
        // Res::build(FAIL)
    }

    pub async fn login(&self, user: UserReq) -> Res<UserVO> {
        // 查询逻辑
        let user_do = match Self::query_user(&self, &user.account_no, &user.password).await {
            Some(user_do) => user_do,
            None => return Res::build(FAIL),
        };
        let mut user_vo: UserVO = user_do.into();
        //加密
        let token = match security_utils::aes_encrypt(&user_vo.id.to_string()) {
            Ok(token) => token,
            Err(_) => return Res::build(FAIL),
        };
        user_vo.token = token;
        let key = SYSTEM_USER.key().format(&[&user_vo.id.to_string()]);
        //删除缓存
        GlobalCache::del(&key);
        let sys_user: SysUser = SysUser {
            id: user_vo.id.clone(),
            account_no: user_vo.account_no.clone(),
            name: user_vo.name.clone(),
            status: user_vo.status.clone(),
        };
        //放入缓存
        GlobalCache::set(key, serde_json::to_string(&sys_user).unwrap());
        Res::success(user_vo)
    }

    /**
     * 查询用户
     */
    async fn query_user(&self, account_no: &str, pwd: &str) -> Option<UserModel> {
        let user = UserModel {
            id: 1912753992656158721,
            name: Some("admin".to_string()),
            account_no: Some("admin".to_string()),
            status: Some(true),
            ..Default::default()
        };
        Some(user)
    }
}
